package com.dong.binaryTree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Classname InvertTree
 * @Description 翻转二叉树
 * @Date 2022/4/8 9:22
 * @Author dcz
 */
public class InvertTree {

    //前序遍历翻转
    public TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }
        swapChildren(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public void swapChildren(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

    //迭代
    public TreeNode invertTree2(TreeNode root) {
        if (root==null){
            return null;
        }
        //将二叉树中的节点逐层放入队列中，再迭代处理队列中的元素
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            //每次都从队列中拿一个节点，并交换这个节点的左右子树
            TreeNode tmp = queue.poll();
            TreeNode left = tmp.left;
            tmp.left = tmp.right;
            tmp.right = left;
            //如果当前节点的左子树不为空，则放入队列等待后续处理
            if (tmp.left!=null){
                queue.add(tmp.left);
            }
            if (tmp.right!=null){
                queue.add(tmp.right);
            }
        }
        return root;

    }

}
